package com.zz.yt.lib.ui.base.mvp;


import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.whf.android.jar.app.Latte;
import com.whf.android.jar.base.mvp.BasePresenter;
import com.whf.android.jar.base.mvp.IModel;
import com.whf.android.jar.base.mvp.IView;
import com.whf.android.jar.net.HttpCode;
import com.whf.android.jar.net.callback.ISuccess;
import com.whf.android.jar.net.gson.HttpGsonUtils;
import com.whf.android.jar.util.log.LatteLogger;
import com.zz.yt.lib.annex.QbSdkUtils;
import com.zz.yt.lib.annex.listener.OnClickAnnexLoading;
import com.zz.yt.lib.annex.picture.bean.FilePathBean;
import com.zz.yt.lib.annex.popup.PicturePopup;
import com.zz.yt.lib.ui.base.IResponse;
import com.whf.android.jar.popup.listener.OnClickDecisionListener;
import com.zz.yt.lib.ui.listener.OnClickStringListener;
import com.zz.yt.lib.ui.popup.view.TipsMinPopup;
import com.zz.yt.lib.ui.utils.ObjUtils;

import java.util.ArrayList;
import java.util.List;

import me.yokeyword.fragmentation.anim.DefaultHorizontalAnimator;
import me.yokeyword.fragmentation.anim.FragmentAnimator;

/***
 * 界面
 * @author qf
 * @version 1.0.23
 */
public abstract class LatteMvpFragment<M extends IModel, V extends IView, P extends BasePresenter<M, V>>
        extends PerCheckerMvpFragment<M, V, P> implements IResponse, OnClickAnnexLoading {

    private static final String TAG_OFFSET = "TAG_OFFSET";
    private static final int KEY_OFFSET = -123;

    protected ArrayList<String> mFileIdArray = new ArrayList<>();
    /**
     * 判断上一个界面是否传过来bundle
     */
    protected boolean hasData;

    /**
     * 处理上一个页面传来的数据
     */
    protected void getData(Bundle bundle) {

    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        final Bundle mBundle = getArguments();
        if (mBundle != null) {
            hasData = true;
            getData(mBundle);
        }
    }

    @Override
    public FragmentAnimator onCreateFragmentAnimator() {
        return new DefaultHorizontalAnimator();
    }

    /**
     * Add the top margin size equals status bar's height for view.
     *
     * @param view The view.(只能使用，不建议重构)
     */
    protected final void addMarginTopEqualStatusBarHeight(@NonNull View view) {
        view.setTag(TAG_OFFSET);
        Object haveSetOffset = view.getTag(KEY_OFFSET);
        if (haveSetOffset != null && (Boolean) haveSetOffset) {
            return;
        }
        ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        layoutParams.setMargins(layoutParams.leftMargin,
                layoutParams.topMargin + getStatusBarHeight(),
                layoutParams.rightMargin,
                layoutParams.bottomMargin);
        view.setTag(KEY_OFFSET, true);
    }

    private int getStatusBarHeight() {
        int resourceId = Latte.getBarHeight();
        return resourceId == -1 ? 36 : resourceId;
    }

    /**
     * @return 是否是全屏
     */
    protected boolean isTopView() {
        return true;
    }


    @Override
    public void inFile(@NonNull String fileUrl) {
        final String name = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
        download(fileUrl, name, new ISuccess() {
            @Override
            public void onSuccess(String response) {
                hideLoading();
                QbSdkUtils.openFileReader(Latte.getActivity(), response, null, null);
            }
        });
    }

    @Override
    public void onSuccessPath(String data) {
        hideLoading();
        if (!TextUtils.isEmpty(data) && data.length() > 1) {
            if ("[".equals(data.substring(0, 1))) {
                final List<FilePathBean> filePathArray = HttpGsonUtils.fromJsonList(data, FilePathBean.class);
                if (filePathArray != null && !filePathArray.isEmpty()) {
                    for (FilePathBean filePath : filePathArray) {
                        setFilePath(filePath);
                    }
                }
            } else {
                final FilePathBean filePath = HttpGsonUtils.fromJson(data, FilePathBean.class);
                setFilePath(filePath);
            }
        }
    }
    /**
     * @param filePath:上传附件的回调解析的对象。
     */
    protected void setFilePath(FilePathBean filePath) {
        if (filePath != null) {
            //保存上传文件的id
            mFileIdArray.add(getIdFile(filePath));
        }
    }

    /**
     * @param filePathBean:取出上传附件的id
     */
    protected String getIdFile(FilePathBean filePathBean) {
        if (filePathBean == null) {
            return null;
        }
        return filePathBean.getId();
    }

    @Override
    public boolean isFile() {
        if (mFileIdArray.size() == 0) {
            ToastUtils.showShort("请选择文件上传");
            return true;
        }
        return false;
    }

    @Override
    public String getFile() {
        return ObjUtils.getFieldArrayId(mFileIdArray);
    }

    /**
     * @param response:默认返回处理
     * @param listener：返回的data
     */
    protected void code(String response, OnClickStringListener listener) {
        hideLoading();
        if (ObjectUtils.isEmpty(response) || listener == null) {
            return;
        }
        LatteLogger.json(response);
        final int code = ObjUtils.getCode(response);
        if (HttpCode.CODE_200 == code) {
            final String data = ObjUtils.getData(response);
            listener.onClick(data);
        } else {
            onError(code, Latte.getMessage(response));
        }
    }

    /***
     * 提交数据
     */
    protected void save(OnClickDecisionListener listener) {
        KeyboardUtils.hideSoftInput(mRootView);
        TipsMinPopup.create()
                .setTitle("是否确认提交")
                .setOnClickListener(listener)
                .popup();
    }

    /***
     * 提交数据
     */
    protected void save(PicturePopup.OnClickListener listener) {
        KeyboardUtils.hideSoftInput(mRootView);
        PicturePopup.create(Latte.getActivity())
                .setPhotograph("提交")
                .setLocal("保存")
                .setClickListener(listener)
                .popup();
    }

}
